package com.code2roc.fastboot.framework.extra.sqllog;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(value = 70)
public class SqlLogAspect {
    @Pointcut("@annotation(com.code2roc.fastboot.framework.extra.sqllog.IgnoreSqlLog) " +
            "|| @within(com.code2roc.fastboot.framework.extra.sqllog.IgnoreSqlLog)")
    public void sqlLogAspect() {

    }

    @Around("sqlLogAspect()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();
        IgnoreSqlLog classIgnoreSqlLog = (IgnoreSqlLog)targetClass.getAnnotation(IgnoreSqlLog.class);
        IgnoreSqlLog methodIgnoreSqlLog = method.getAnnotation(IgnoreSqlLog.class);
        if (classIgnoreSqlLog != null) {
            SqlLogContextHolder.setTag(targetClass.getName());
        }
        else if (methodIgnoreSqlLog != null) {
            SqlLogContextHolder.setTag(targetClass.getName() + "." + method.getName());
        }
        try {
            return point.proceed();
        } finally {
            if (classIgnoreSqlLog != null || methodIgnoreSqlLog!=null) {
                SqlLogContextHolder.cleatTag();
            }
        }
    }
}
